/*
 * The contents of this web application are subject to the Mozilla Public License Version 
 * 1.1 (the "License"); you may not use this web application except in compliance with 
 * the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, 
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
 * for the specific language governing rights and limitations under the License.
 * 
 * The Original Code is owned by and the Initial Developer of the Original Code is 
 * Composite A/S (Danish business reg.no. 21744409). All Rights Reserved
 * 
 * Section 11 of the License is EXPRESSLY amended to include a provision stating 
 * that any dispute, including but not limited to disputes related to the enforcement 
 * of the License, to which Composite A/S as owner of the Original Code, as Initial 
 * Developer or in any other role, becomes a part to shall be governed by Danish law 
 * and be initiated before the Copenhagen City Court ("K�benhavns Byret")            
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Composite.Core.Types;
using Composite.Core.Xml;


namespace Composite.Data.DynamicTypes
{
    /// <summary>    
    /// </summary>
    /// <exclude />
    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] 
	public static class DynamicTypeMarkupServices
	{
        private static readonly XName _fieldReferenceElementName = Namespaces.DynamicData10 + "fieldreference";
        private static readonly XName _fieldReferenceTypeAttributeName = "typemanagername";
        private static readonly XName _fieldReferenceFieldAttributeName = "fieldname";


        /// <exclude />
        public static XElement GetReferenceElement(this DataFieldDescriptor fieldToReference, DataTypeDescriptor ownerTypeDescriptor)
        {
            return GetReferenceElement(fieldToReference.Name,ownerTypeDescriptor.TypeManagerTypeName);
        }


        /// <exclude />
        public static XElement GetReferenceElement(string fieldName, string typeManagerName)
        {
            // ensure "data:" prefix in markup:
            XElement element = XElement.Parse(string.Format("<data:{0} xmlns:data='{1}' />", _fieldReferenceElementName.LocalName, _fieldReferenceElementName.NamespaceName));

            element.Add(
                new XAttribute(_fieldReferenceFieldAttributeName, fieldName),
                new XAttribute(_fieldReferenceTypeAttributeName, typeManagerName));

            return element;
        }


        /// <exclude />
        public static bool TryGetDescriptors(XElement fieldReferenceElement, out DataTypeDescriptor typeDescriptor, out DataFieldDescriptor fieldDescriptor)
        {
            typeDescriptor = null;
            fieldDescriptor = null;

            if (fieldReferenceElement.Name != _fieldReferenceElementName)
            {
                throw new InvalidOperationException(string.Format("Unexpected element name '{0}'. Expected '{1}'",
                                                                  fieldReferenceElement.Name, _fieldReferenceElementName));
            }

            string typeManagerName = fieldReferenceElement.Attribute(_fieldReferenceTypeAttributeName).Value;
            string fieldName = fieldReferenceElement.Attribute(_fieldReferenceFieldAttributeName).Value;

            Type t = TypeManager.TryGetType(typeManagerName);
            if (t == null)
            {
                return false;
            }

            typeDescriptor = DynamicTypeManager.GetDataTypeDescriptor(t.GetImmutableTypeId());
            if (typeDescriptor == null)
            {
                return false;
            }

            if(fieldName == "DataSourceId")
            {
                fieldDescriptor = new DataFieldDescriptor(Guid.Empty, "DataSourceId", StoreFieldType.LargeString, typeof (string));
                return true;
            }

            fieldDescriptor = typeDescriptor.Fields.Where(f => f.Name == fieldName).FirstOrDefault();
            if (fieldDescriptor == null)
            {
                return false;
            }
            
            return true;
        }



        /// <exclude />
	    public static IEnumerable<FieldReferenceDefinition> GetFieldReferenceDefinitions(XContainer container, string typeManagerName)
        {
            Type type = null;

            foreach (XElement referenceElement in container.Descendants(_fieldReferenceElementName))
            {
                string referencedTypeName = referenceElement.Attribute(_fieldReferenceTypeAttributeName).Value;

                if(referencedTypeName != typeManagerName)
                {
                    type = type ?? TypeManager.TryGetType(typeManagerName);
                    if(type == null) continue;

                    Type referencedType = TypeManager.TryGetType(referencedTypeName);
                    if(referencedType == null || !referencedType.Equals(type))
                    {
                        continue;
                    }
                }

                string fieldName = referenceElement.Attribute(_fieldReferenceFieldAttributeName).Value;

                yield return new FieldReferenceDefinition { FieldName = fieldName, FieldReferenceElement = referenceElement };
            }
        }


        /// <exclude />
        public class FieldReferenceDefinition
        {
            /// <exclude />
            public string FieldName { get; set; }

            /// <exclude />
            public XElement FieldReferenceElement { get; set; }
        }
	}
}
